const express = require('express');
const router = express.Router();
const User = require('../models/User')
const Card = require('../models/Card');
const indexTabs = require('../config/config');

router.patch('/update/user/:uid', async (req, res) => {
    try {
        const uid = req.params.uid;
        const updatedUserInfo = req.body;
        const updatedUser = await User.findOneAndUpdate({ uid }, updatedUserInfo, { new: true });
        if (!updatedUser) {
            res.status(404).json({ message: '用户不存在' });
        }
        console.log(updatedUser);
        res.status(200).json({ message: '用户信息已成功更新' });
    } catch (error) {
        res.status(500).json({ message: '更新用户信息失败' });
        console.error('更新用户信息失败:', error);
    }
})

router.get('/getFollow', async (req, res) => {
    try {
        const id = req.query._id;
        const user = await User.findById(id);
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        const followingIds = user.followingCount;
        const followingUsers = await User.find({ uid: { $in: followingIds } }, '_id uid avatar username');
        const formattedFollowing = followingUsers.map(followingUser => ({
            _id: followingUser._id,
            uid: followingUser.uid,
            avatar: followingUser.avatar,
            username: followingUser.username,
        }));
        res.status(200).json(formattedFollowing);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Internal Server Error' });
    }
});


// Follow or Unfollow a user
router.post('/follow', async (req, res) => {
    try {
        const followerUid = req.body.params.followerUid;
        const followingUid = req.body.params.followingUid;
        const followerUser = await User.findOne({ uid: followerUid });
        const followingUser = await User.findOne({ uid: followingUid });
        if (!followerUser || !followingUser) {
            return res.status(400).json({ message: 'User not found' });
        }
        // 检查是否已经关注了
        if (followerUser.followingCount.includes(followingUid)) {
            return res.status(201).json({ message: '已关注该用户', isFollow: true });
        }
        await User.updateOne({ uid: followerUid }, { $push: { followingCount: followingUid } });
        await User.updateOne({ uid: followingUid }, { $inc: { followersCount: 1 } });
        res.status(200).json({ message: '关注成功' });
    } catch (error) {
        console.error('Follow/Unfollow user failed:', error);
        res.status(500).json({ message: 'Follow/Unfollow user failed' });
    }
});
// 取关用户
router.post('/unfollow', async (req, res) => {
    try {
        const followerUid = req.body.params.followerUid;
        const followingUid = req.body.params.followingUid;
        const user = await User.findOne({ uid: followerUid });
        const _id = user._id;
        // 检查是否已关注
        const followerUser = await User.findOne({ _id: _id });
        if (!followerUser) {
            return res.status(400).json({ message: '找不到关注者用户' });
        }
        if (!followerUser.followingCount.includes(followingUid)) {
            return res.status(201).json({ message: '未关注该用户' });
        }
        await User.findByIdAndUpdate(_id, { $pull: { followingCount: followingUid } });
        console.log('关注了');
        // 更新被关注用户的粉丝数量之前，确保粉丝数量不会成为负数
        const followingUser = await User.findOne({ uid: followingUid });
        if (!followingUser) {
            return res.status(400).json({ message: '找不到被关注者用户' });
        }
        if (followingUser.followersCount > 0) {
            // 只有在粉丝数量大于0时才减1，避免成为负数
            await User.updateOne({ uid: followingUid }, { $inc: { followersCount: -1 } });
        }
        res.status(200).json({ message: '取消关注成功' });
    } catch (error) {
        console.error('取消关注用户失败:', error);
        res.status(500).json({ message: '取消关注用户失败' });
    }
});

module.exports = router;